package com.yisin.ssh2;

import java.io.IOException;
import java.io.InputStream;

import com.yisin.ssh2.jsch.ChannelExec;
import com.yisin.ssh2.jsch.JSchException;
import com.yisin.ssh2.jsch.Util;

public class SshExec extends SshBase {

	public SshExec(String host, String user, String password) {
		super(host, user, password);
	}

	public SshExec(String host, String user) {
		super(host, user);
	}

	protected String getChannelType() {
		return "exec";
	}

	// / <summary>
	// /This function is empty, so no channel is connected
	// /on session connect
	// / </summary>
	protected void ConnectChannel() {
	}

	protected ChannelExec GetChannelExec(String command) throws JSchException {
		ChannelExec exeChannel = (ChannelExec) m_session.openChannel("exec");
		exeChannel.setCommand(command);
		return exeChannel;
	}

	public String RunCommand(String command) throws JSchException, IOException {
		m_channel = GetChannelExec(command);
		InputStream s = m_channel.getInputStream();
		m_channel.connect();
		byte[] buff = new byte[1024];
		StringBuilder res = new StringBuilder();
		int c = 0;
		while (true) {
			c = s.read(buff, 0, buff.length);
			if (c == -1)
				break;
			res.append(Util.getStringAscii(buff, 0, c));
		}
		m_channel.disconnect();
		return res.toString();
	}

	public int RunCommand(String command, String StdOut, String StdErr) throws IOException, JSchException {
		StdOut = "";
		StdErr = "";
		m_channel = GetChannelExec(command);
		InputStream stdout = m_channel.getInputStream();
		InputStream stderr = ((ChannelExec) m_channel).getErrStream();
		m_channel.connect();
		byte[] buff = new byte[1024];
		StringBuilder sbStdOut = new StringBuilder();
		StringBuilder sbStdErr = new StringBuilder();
		int o = 0;
		int e = 0;
		while (true) {
			if (o != -1)
				o = stdout.read(buff, 0, buff.length);
			if (o != -1)
				StdOut += sbStdOut.append(Util.getStringAscii(buff, 0, o));
			if (e != -1)
				e = stderr.read(buff, 0, buff.length);
			if (e != -1)
				StdErr += sbStdErr.append(Util.getStringAscii(buff, 0, e));
			if ((o == -1) && (e == -1))
				break;
		}
		m_channel.disconnect();

		return m_channel.getExitStatus();
	}

	public ChannelExec getChannelExec() {
		return (ChannelExec) this.m_channel;
	}

}
